package com.globant.AutomateEMR;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class NewLogsNotifier {

    public final static String     DOCUMENT_NAME	= "part-r-00000";
    public final static String     INITIAL_MESSAGE	= "Here are words that couldn't be analysed by the parser. " +
    												   " FORMAT: NAME OF FIELD-WORD";
    
    
	public String getNewWordsFromLogs(PropertyLoader prop){
		String message=null;
		try {
			String pathToFolder=prop.readProperty("PathToBucket")+prop.readProperty("PathToNewWords");
			File folder=new File(pathToFolder);
			File[] files=folder.listFiles();
			File document=this.getDocument(files);
			if(document!=null){
				message=this.getMessage(document);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return message;		
	}

	public String getMessage(File document) throws IOException {
		String message=INITIAL_MESSAGE;
		message=message+'\n';
		ArrayList<String> words=this.getWords(document);
		for(int i=0;i<words.size();i++){
			message=message+words.get(i);
			message=message+'\n';
		}
		return message;
	}

	public ArrayList<String> getWords(File document) throws IOException {
		ArrayList<String> words=new ArrayList<String>();
		BufferedReader bf=new BufferedReader(new FileReader(document));
		String s=null;
		while ((s = bf.readLine()) != null) {
			words.add(s);
		}
		bf.close();
		
		return words;
	}

	public File getDocument(File[] files) {
		File result=null;
		for(int i=0;i<files.length;i++){
			System.out.println(files[i].getName());
			if(DOCUMENT_NAME.equals(files[i].getName())){
				result=files[i];
			}
		}
		return result;
	}
}
